package edu.chl.dat255.bluebanana.logic.impl;

import edu.chl.dat255.bluebanana.R;
import java.util.ArrayList;
import android.app.Activity;
import android.database.Cursor;
import android.database.CursorIndexOutOfBoundsException;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.LinearLayout;
import edu.chl.dat255.bluebanana.data.impl.SQLiteStorage;
import edu.chl.dat255.bluebanana.logic.IProfileHandler;
import edu.chl.dat255.bluebanana.presentation.IProfileView;
import edu.chl.dat255.bluebanana.presentation.impl.ProfileView;
import edu.chl.dat255.bluebanana.utils.Observable;
import edu.chl.dat255.bluebanana.utils.Observer;

public class ProMan extends Activity implements Observer {
	private SQLiteStorage db;
	private LinearLayout layout;
	private static IProfileHandler handler;

	private static ArrayList<IProfileView> profileViews = new ArrayList<IProfileView>();

	private Cursor c;

	/** Called when the activity is first created. */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		handler = new ProfileHandler(this);
		handler.deactivateAllProfiles(profileViews);
		handler.addObserver(ProMan.this);

		layout = (LinearLayout) findViewById(R.id.mainLayout);
		db = new SQLiteStorage(this);
		
		setProfiles();
	}
	
	private void setProfiles() {
		db.open();

		c = db.getAllUserProfiles();
		c.moveToFirst();

		try {
			ProfileView profileView = new ProfileView(this, c.getInt(0));
			profileViews.add(profileView);
			layout.addView(profileView);
			profileView.addObserver(handler);

		} catch (CursorIndexOutOfBoundsException e) {
			// The database is empty, insert default profiles instead
			db.insertDefaultProfiles();
			setProfiles();
		}

		while (c.moveToNext()) {
			ProfileView profileView = new ProfileView(this, c.getInt(0));
			profileViews.add(profileView);
			layout.addView(profileView);
			profileView.addObserver(handler);
		}

		db.close();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.layout.menu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle item selection
		switch (item.getItemId()) {
		case R.id.advanced_Settings:
			// TODO: something..
			return true;
		case R.id.add_profile:
			db.open();
			long id = db.addProfile();
			db.close();

			ProfileView profileView = new ProfileView(this, id);
			profileViews.add(profileView);
			layout.addView(profileView);
			profileView.addObserver(handler);
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	@Override
	public void update(Observable parent, Object state) {
		 handler.deactivateAllProfiles(profileViews);
	}
}